package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;

/**
 * 2025/5/7 17:53
 */
@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    /**
     * 切入点
     */
    @Pointcut("@annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut() {
    }

    /**
     * 前置通知
     */
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) {
        log.info("开始进行公共字段自动填充...");

        if (!(joinPoint.getSignature() instanceof MethodSignature)) {
            return;
        }

        // 获取当前被拦截的方法签名
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        //获取被拦截方法的注解
        AutoFill autoFill = methodSignature.getMethod().getAnnotation(AutoFill.class);
        if (autoFill == null) {
            return;
        }
        //获取注解中的参数类型
        OperationType value = autoFill.value();
        //获取当前被拦截方法的参数
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        Object obj = args[0];
        LocalDateTime localDateTime = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();
        try {
            obj.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class).invoke(obj, localDateTime);
            obj.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class).invoke(obj, currentId);
            if (value == OperationType.INSERT) {
                obj.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class).invoke(obj, localDateTime);
                obj.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class).invoke(obj, currentId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("公共字段自动填充失败:{}"+e.getMessage());
        }

    }

}
